package com.wisdom.benefit.jufa.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatTextView;

import com.wisdom.benefit.jufa.utils.DisplayUtil;

/**
 * BorderTextView
 * Created by zhoudawei on 2017/12/11.
 */

public class BorderTextView extends AppCompatTextView {

    private Paint mPaint;
    private int mBorderColor;
    private int mStrokeWidth;//线宽
    private RectF mRectF = new RectF();
    private int mRadius;//圆角半径
    private boolean mOnlyBorder = true;//是否只绘制边框

    public BorderTextView(Context context) {
        this(context, null);
    }

    public BorderTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BorderTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mBorderColor = Color.TRANSPARENT;
        mStrokeWidth = DisplayUtil.dip2px(getContext(), 1);
        mRadius = DisplayUtil.dip2px(getContext(), 5);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(mBorderColor);
        mPaint.setStyle(mOnlyBorder ? Paint.Style.STROKE : Paint.Style.FILL_AND_STROKE);
        mPaint.setStrokeWidth(mStrokeWidth);
    }

    public void setBorderColor(int borderColor) {
        this.mBorderColor = borderColor;
        mPaint.setColor(mBorderColor);
        postInvalidate();
    }

    public void setStrokeWidth(int strokeWidth) {
        this.mStrokeWidth = strokeWidth;
        mPaint.setStrokeWidth(mStrokeWidth);
        postInvalidate();
    }

    public void setRadius(int radius) {
        this.mRadius = radius;
        postInvalidate();
    }

    public void setOnlyBorder(boolean onlyBorder) {
        this.mOnlyBorder = onlyBorder;
        mPaint.setStyle(onlyBorder ? Paint.Style.STROKE : Paint.Style.FILL_AND_STROKE);
        postInvalidate();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldW, int oldH) {
        super.onSizeChanged(w, h, oldW, oldH);
        mRectF.set(mStrokeWidth / 2f + 1,
                mStrokeWidth / 2f + 1,
                w - mStrokeWidth / 2 - 1,
                h - mStrokeWidth / 2 - 1);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawRoundRect(mRectF, mRadius, mRadius, mPaint);
        super.onDraw(canvas);
    }
}
